import Cookie from 'js-cookie'
import CryptoJS from 'crypto-js';

export function getToken () {
  return Cookie.get('UNI_LOGIN_TOKEN')
}
export function setToken (token) {
  return Cookie.set('UNI_LOGIN_TOKEN', token)
}

export function setCookie (name, content) {
  if (!name) return
  if (typeof content !== 'string') {
    Cookie.set(name, JSON.stringify(content))
  } else {
    Cookie.set(name, content)
  }
}

export function getCookie (name) {
  if (!name) return
  return Cookie.get(name)
}

export function isEmail (email) {
  /* eslint-disable */
  return /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,6})$/.test(
    email
  )
}

export function isPassword (password) {
  // return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z!@#$%^&*-_]{8,16}$/.test(password);
  // return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/.test(password)
  return /^(?=.*\d)(?=.*[a-zA-Z])[0-9A-Za-z!-/:-@^-~]{8,16}$/.test(password)
}

export function isImage (url) {
  const index = url.lastIndexOf('.')
  const ext = url.substring(index + 1)
  return ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].includes(ext.toLowerCase())
}

export function isVideo (url) {
  const index = url.lastIndexOf('.')
  const ext = url.substring(index + 1)
  return ['avi', 'wmv', 'mkv', 'mp4', 'mov', 'rm', '3gp', 'flv', 'mpg', 'rmvb'].includes(ext.toLowerCase())
}

export function objToQuery (obj) {
  // 首先判断obj是否为真，为真则进行处理，不然直接return
  if (obj) {
    // 定义变量接收query字符串
    let query = ''
    // 循环遍历对象
    for (const key in obj) {
      // 定义变量接收对象的value值
      let value = obj[key]
      // 若对象的value值为数组，则进行join打断
      if (Array.isArray(value)) {
        value = value.join(',')
      }
      // 进行字符串拼接
      query += `&${key}=${value}`
    }
    // replace返回一个新的字符串，要用query重新接受一下，并把第一个&替换为?
    query = query.replace('&', '?')
    // 返回生成的query字符串
    return query
  }
  return ''
}

// 获取滚动条宽度,此方法必须在mounted后调用
let scrollWidth
export function getScrollWidth () {
  if (process.server) return
  if (scrollWidth !== undefined) return scrollWidth
  const oDiv = document.createElement('DIV')
  oDiv.style.cssText = 'position:absolute; top:-9999px; width:100px;height:100px; overflow:hidden;'
  const noScroll = document.body.appendChild(oDiv).clientWidth
  oDiv.style.overflowY = 'scroll'
  const scroll = oDiv.clientWidth
  document.body.removeChild(oDiv)
  scrollWidth = noScroll - scroll
  return scrollWidth
}

export function throttle (fn, wait) {
  const callback = fn
  let timerId = null

  // 是否是第一次执行
  let firstInvoke = true

  function throttled () {
    const context = this
    const args = arguments

    // 如果是第一次触发，直接执行
    if (firstInvoke) {
      callback.apply(context, args)
      firstInvoke = false
      return
    }

    // 如果定时器已存在，直接返回。
    if (timerId) {
      return
    }

    timerId = setTimeout(function () {
      // 注意这里 将 clearTimeout 放到 内部来执行了
      clearTimeout(timerId)
      timerId = null

      callback.apply(context, args)
    }, wait)
  }

  // 返回一个闭包
  return throttled
}
// immediate 表示第一次是否立即执行
export function debounce(fn, wait = 50, immediate = false) {
  let timer = null
  return function(...args) {
    // this保存给context
    const context = this
    if (timer) clearTimeout(timer)

    // immediate 为 true 表示第一次触发后执行
    // timer 为空表示首次触发
    if (immediate && !timer) {
      fn.apply(context, args)
    }

    timer = setTimeout(() => {
      fn.apply(context, args)
    }, wait)
  }
}
export function encryptPassWord(value) {
  const aseKey = CryptoJS.enc.Utf8.parse('5yuy675489834ert');
  const encrypted = CryptoJS.AES.encrypt(value, aseKey, {
    iv: aseKey,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding,
  });
  return encrypted.toString();
}
